<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2019-11-27
 * Time: 11:24
 */

namespace app\api\service;

use app\api\model\Member;
use app\api\model\PickDeliverStaff;
use app\api\model\ProductOrder;
use app\api\model\User;
use app\api\model\UserInvitation;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\ParameterException;
use app\lib\exception\TokenException;
use think\Exception;
use think\facade\Request;
use think\facade\Cache;

class Token
{
    /**
     * 生成token值
     */
    public function generateToken()
    {
        //32字符组成的一组随机字符串
        $randChars = getRandChar(32);
        //三组字符串进行md5加密
        $timestamp = $_SERVER['REQUEST_TIME'];
        //salt
        $salt = config('secure.token_salt');
        return md5($randChars.$timestamp.$salt);
    }

    //根据token获取缓存中某一个字段的值
    public static function getCurrentTokenVar($key){
        $token = Request::instance()
            ->header('token');
        $vars = Cache::get($token);
        if(!$vars){
            throw new TokenException();
        }else{
            if(!is_array($vars)){
                $vars = json_decode($vars,true);
            }
            if(array_key_exists($key,$vars)){
                return $vars[$key];
            }else{
                throw new Exception('尝试获取的token变量不存在');
            }
        }
    }

    public static function getCurrentUid(){
        $uid = self::getCurrentTokenVar('uid');
        $user = User::get($uid);
        if(!$user) {
            throw new TokenException();
        }
        return $uid;
    }

    //用户和管理员都可以访问的接口权限
    public static function needPrimaryScope(){
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope >= ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }
    }

    //只有用户才可以访问的接口权限
    public static function needExclusiveScope()
    {
        $scope = self::getCurrentTokenVar('scope');
        if($scope)
        {
            if($scope == ScopeEnum::User)
            {
                return true;
            }
            else{
                throw new ForbiddenException();
            }
        }
        else{
            throw new TokenException();
        }

    }

    /**
     * 验证用户token
     */
    public static function verifyToken($token)
    {
        $exist = Cache::get($token);
        if($exist)
        {
            return true;
        }
        else{
            return false;
        }
    }


    protected static function makeOrderNo()
    {
        $yCode = array('A','B','C','D','E','F','G','H','I','J');
        $orderSn =
            $yCode[intval(date('Y')) - 2021] . strtoupper(dechex(date('m'))) . date('d') .
            substr(time(),-5) . substr(microtime(),2,5) . sprintf('%02d',rand(0,99));
        return $orderSn;
    }

    /**
     * 获取产品价格
     */
    public static function getProductPrice($product)
    {
        $uid = self::getCurrentUid();
        $userInvitation = UserInvitation::where('invitee',$uid)->find();
        $userInfoOne = User::get($userInvitation['inviter']);
        if($userInfoOne['type'] == 1) {
            $order = ProductOrder::where('status','gt',1)
                ->where('user_id','eq',$uid)
                ->find();
            if($order) {
                $product['price'] = $product['present_price'];
            } else {
                $product['price'] = $product['new_user_price'];
            }
        } else {
            $product['price'] = $product['present_price'];
        }
        return $product;
    }


    /**
     * 生成订单的分享二维码
     */
    public function setCode($order_id)
    {
        $data['scene'] = 'order-'.$order_id;
        $data['width'] = 280;
        $data['page'] = 'pages/order/hexiao';
        $name = 'order_'.$order_id;
        $this->setCodePub($data,$name);
    }

    public function setCodePub($data,$name)
    {
        $wxCodeUrl = sprintf(config('wx.code_url'),
            config('wx.app_id'),config('wx.app_secret'));
        $access_token = Cache::get('access_token');
        if(!$access_token)
        {
            $jsonInfo = curl_get($wxCodeUrl);
            $access_token = $jsonInfo["access_token"];
            $expire_in = config('setting.token_expire_in');
            $result = cache('access_token',$access_token,$expire_in);
            if(!$result)
            {
                throw new TokenException([
                    'msg' => '服务器缓存异常',
                    'errorCode' => 10005
                ]);
            }
        }
        $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=".$access_token;
        $wxResult = https_post($url,json_encode($data));
        if(strstr($wxResult, 'errcode')) {
            $jsonInfo = curl_get($wxCodeUrl);
            $access_token = $jsonInfo["access_token"];
            $expire_in = config('setting.token_expire_in');
            $result = cache('access_token', $access_token, $expire_in);
            if (!$result) {
                throw new TokenException([
                    'msg' => '服务器缓存异常',
                    'errorCode' => 10005
                ]);
            }
            $url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" . $access_token;
            $wxResult = https_post($url, json_encode($data));
        }
        $file = fopen(config('setting.xd_prefix') . $name . '.png', "w");//打开文件准备写入
        fwrite($file, $wxResult);//写入,$res为图片二进制内容
        fclose($file);//关闭
    }
}